Coding3 - π Connecting to MongoDB
π§ What Youβll Learnβ
In this lesson, youβll:
- Set up MongoDB for your project
- Create a reusable connection file using Mongoose
- Load the connection string from the
.env
file
β Step 1: Install Mongooseβ
In your terminal, run:
npm install mongoose
npm install --save-dev @types/mongoose
β
Step 2: Add Your MongoDB URI to .env
β
Update your .env
file:
SERVER_PORT=5000
MONGODB_URI=mongodb://localhost:27017/my-api
π‘ Replace
my-api
with your preferred database name.
β Step 3: Create MongoDB Connection Fileβ
File: src/dbconnect.ts
import mongoose from "mongoose";
const connectDB = async (mongoURI: string) => {
try {
await mongoose.connect(mongoURI);
console.log('β
MongoDB Connected: ', mongoURI);
} catch (error) {
console.error('β MongoDB connection failed:', error);
process.exit(1); // exit app if connection fails
}
}
export default connectDB;
β This file handles the connection to your MongoDB database and shows a helpful log message.
β
Step 4: Use connectDB()
in app.ts
β
Update your src/app.ts
to use the connection:
import 'dotenv/config';
import express from 'express';
import connectDB from './dbconnect';
const app = express();
const PORT = process.env.SERVER_PORT || 5000;
// π§ Connect to MongoDB
connectDB(process.env.MONGODB_URI || '');
// Middleware
app.use(express.json());
// Test Route
app.get('/health', (_req, res) => {
res.json({ message: 'Ok' });
});
// Start Server
app.listen(PORT, () => {
console.log(`π Server running at http://localhost:${PORT}`);
});
π§ͺ Step 5: Run and Verifyβ
Run your project:
npm start
β You should see something like:
β
MongoDB Connected: mongodb://localhost:27017/my-api
π Server running at http://localhost:5000
π¦ Folder Structure So Farβ
REST-API/
βββ src/
β βββ app.ts
β βββ dbconnect.ts
βββ .env
βββ nodemon.json
βββ package.json
βββ tsconfig.json
β Whatβs Next?β
In Lesson 4, youβll create your User model and build a user authentication system using signup, login, and logout routes.